import { request } from '../../request/index';
import regeneratorRuntime from '../../lib/runtime/runtime';

Page({
  data: {
    goodsObj: {},
    // 商品收藏未被选中
    isCollect: false,
    showIndex:0,
    //商品数量
    goodsNumber: 1,
    showPop: false,
    animationData: {},
    minusStatus: 'disabled'  
  },
  //商品对象
  GoodsInfo: {},
  onLoad(options) {
    wx.showLoading({
      title: '加载中',
    })
    const {id} = options;
    console.log(id);
    const goodsObj = wx.getStorageSync('goodsObj')
    const collect = wx.getStorageSync('collect')
    if(!goodsObj) {
      this.getGoodsDetail(id);
    }
    if(goodsObj._id !== id) {
      this.getGoodsDetail(id);
    } else {
      collect.forEach(item => {
        if(item._id == id) {
          this.setData({
            isCollect: item.isCollect
          })
        }
      })
      this.setData({
        goodsObj,
      })
      this.GoodsInfo = this.data.goodsObj;
    }
    setTimeout(function () {
      wx.hideLoading()
    }, 1500)
  },
  async getGoodsDetail(id) {
    wx.cloud.database().collection("goodsList").doc(id)
   .get()
   .then(res => {
     console.log(res);
     this.setData({
      goodsObj: res.data,
      isCollect: res.data.isCollect
     })
     wx.setStorageSync('goodsObj', this.data.goodsObj)
     this.GoodsInfo = this.data.goodsObj;
   })
    let collect = wx.getStorageSync('collect') || [];
    let isCollect = collect.some(v => v.goods_id === this.GoodsInfo.goods_id);
    this.setData({
      isCollect
    })
  },
  //点击加入购物车
  handleAddCart(e) {
    console.log(this.GoodsInfo);
    let status = e.currentTarget.dataset.status
    //1.获取缓存中的购物车数组
    let cart = wx.getStorageSync('cart') || [];
    //2.判断 当前的商品是否已经存在于 购物车
    let index = cart.findIndex(v => v.goods_id === this.GoodsInfo.goods_id);
    if(index === -1) {
      //3.购物车中不存在该商品说明还未添加
      if(status == 'in') {
        this.GoodsInfo.num = this.data.goodsNumber;
      } else {
        this.GoodsInfo.num = 1;
      }
      this.GoodsInfo.checked = true;
      cart.push(this.GoodsInfo);
    }else{
      //4.购物车中已经存在该商品数据 执行num++
      cart[index].num++;
    }
    //5.把购物车重新添加回缓存中
    wx.setStorageSync("cart", cart);
    //6.弹窗提示
    wx.showToast({
      title: '加入成功',
      icon: 'success',
      mask: true //mask为true是为了防止用户手抖或疯狂点击按钮导致一次性添加太多，这样可以停顿1.5秒后再继续
    });
  },
  // 点击收藏商品
  handleCollect() {
    let isCollect = false;
    // 1.获取缓存中的商品数据
    let collect = wx.getStorageSync('collect') || [];
    // 2.判断该商品是否被收藏过
    let index = collect.findIndex(v => v.goods_id === this.GoodsInfo.goods_id);
    // 3.当index ！== -1时说明商品已经被收藏过了
    if(index !== -1) {
      // 在数组中删除该商品
      collect.splice(index, 1);
      isCollect = false;
      wx.cloud.callFunction({
        name: 'updcollect',
        data: {
          id: this.GoodsInfo._id,
          isCollect: isCollect
        }
      })
      .then(res => {
        console.log('云函数取消收藏',res);
        // 6.弹窗提示
        wx.showToast({
          title: '取消收藏成功',
          icon: 'success',
          mask: true
        });
        this.setData({
          isCollect
        })
      })
    }else {
      // 没有收藏过
      collect.push(this.GoodsInfo);
      isCollect = true;
      wx.cloud.callFunction({
        name: 'updcollect',
        data: {
          id: this.GoodsInfo._id,
          isCollect: isCollect
        }
      })
      .then(res => {
        console.log('云函数添加收藏',res);
      })
      wx.showToast({
        title: '收藏成功',
        icon: 'success',
        mask: true
      });
      this.setData({
        isCollect
      })
    }
    // 4.把数组重新存入到缓存中
    wx.setStorageSync('collect', collect);
    // 5.修改data中的属性
    this.setData({
      isCollect
    })
  },
  // 折叠面板
  panel(e) {
    if (e.currentTarget.dataset.index != this.data.showIndex) {
      this.setData({
        showIndex: e.currentTarget.dataset.index
      })
    } else {
      this.setData({
        showIndex: 0
      })
    }
  },
  // 显示底部弹层
  showModal: function() {
    var _this = this;
    var animation = wx.createAnimation({
      duration: 500,
      timingFunction: 'ease',
      delay: 0
    })
    _this.animation = animation
    animation.translateY(300).step()
    _this.setData({
      animationData: animation.export(),
      showPop: true
    })
    setTimeout(function() {
      animation.translateY(0).step()
      _this.setData({
        animationData: animation.export()
      })
    }.bind(_this), 50)
  },
  // 隐藏底部弹层
  hideModal: function() {
    var _this = this;
    // 隐藏遮罩层
    var animation = wx.createAnimation({
      duration: 500,
      timingFunction: "ease",
      delay: 0
    })
    _this.animation = animation
    animation.translateY(300).step()
    _this.setData({
      animationData: animation.export(),
    })
    setTimeout(function() {
      animation.translateY(0).step()
      _this.setData({
        animationData: animation.export(),
        showPop: false
      })
    }.bind(this), 200)
  },
  reduceNumber() {
    var num = this.data.goodsNumber;  
    // 如果大于1时，才可以减  
    if (num > 1) {  
        num --;  
    }  
    // 只有大于一件的时候，才能normal状态，否则disable状态  
    var minusStatus = num <= 1 ? 'disabled' : 'normal';  
    // 将数值与状态写回  
    this.setData({  
      goodsNumber: num,  
      minusStatus: minusStatus  
    });  
  },
  inputValueChange(e) {
    this.setData({
      goodsNumber: e.detail.value
    })
  },
  addNumber() {
    var num = this.data.goodsNumber;  
    // 不作过多考虑自增1  
    num ++;  
    // 只有大于一件的时候，才能normal状态，否则disable状态  
    var minusStatus = num < 1 ? 'disabled' : 'normal';  
    // 将数值与状态写回  
    this.setData({  
      goodsNumber: num,  
      minusStatus: minusStatus  
    });  
  },
  // 放大预览
  handlePreview(e) {
    const urls = this.GoodsInfo.swiperimg
    const current = e.currentTarget.dataset.urls
    wx.previewImage({
      current,
      urls
    })
  }
})